package com.ticket.sass.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.dto.input.coupons.code.CouponCodeListInput;
import com.ticket.sass.admin.mapper.CouponCodeMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.CouponCodeEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-07-04
 */
@Service
public class CouponCodeServiceImpl extends ServiceImpl<CouponCodeMapper, CouponCodeEntity> implements BaseService<CouponCodeEntity> {
    public IPage<CouponCodeEntity> iPage(Long couponId, CouponCodeListInput input, List<String> codes) {
        IPage<CouponCodeEntity> page = new Page<>(input.getPageNum(), input.getPageSize());
        QueryWrapper<CouponCodeEntity> queryWrapper = new QueryWrapper<>();
        if (input.getBatchNum() != null) {
            queryWrapper.lambda().like(CouponCodeEntity::getBatchNum, input.getBatchNum());
        }
        
        if (input.getCode() != null) {
            queryWrapper.lambda().like(CouponCodeEntity::getCode, input.getCode());
        }
        

        if (Objects.isNull(input.getUseState())){
        
        } else if (1 == input.getUseState()){
            if (codes.size() == 0){
                return new Page<>();
            }
            queryWrapper.in(codes.size() > 0, "code", codes);
        } else if (0 == input.getUseState()){
            queryWrapper.notIn(codes.size() > 0, "code", codes);
        }
        
   
        queryWrapper.eq("coupon_id", couponId);
        queryWrapper.eq(Objects.nonNull(input.getTake()), "is_take", input.getTake());
        queryWrapper.orderByDesc("id");
        return this.page(page, queryWrapper);
    }
    
    public Map<String, Integer> getCouponCodeCountByBatchNumsAndCouponId(List<String> batchNums, Long couponId) {
        if (batchNums.size() == 0){
            return new HashMap<>();
        }
        
        QueryWrapper<CouponCodeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("batch_num", batchNums);
        queryWrapper.eq("coupon_id", couponId);
        queryWrapper.select("batch_num", "COUNT(*) AS count");
        queryWrapper.groupBy("batch_num");
        
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        return results.stream()
            .collect(Collectors.toMap(map -> map.get("batch_num").toString(), map -> Integer.parseInt(map.get("count").toString())));
    }
    
    // 检查兑换码是否重复，并返回重复的兑换码列表
    public List<String> checkDuplicateCodes(List<CouponCodeEntity> couponCodes) {
        Set<String> existingCodes = new HashSet<>();
        List<String> duplicates = new ArrayList<>();
        
        // 查询数据库中已存在的兑换码
        QueryWrapper<CouponCodeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("code");
        List<String> dbCodes = this.list(queryWrapper).stream()
            .map(CouponCodeEntity::getCode)
            .collect(Collectors.toList());
        
        // 检查新生成的兑换码是否与数据库中的兑换码重复
        for (CouponCodeEntity codeEntity : couponCodes) {
            if (dbCodes.contains(codeEntity.getCode())) {
                duplicates.add(codeEntity.getCode());
            } else {
                existingCodes.add(codeEntity.getCode());
            }
        }
        
        // 更新数据库中的兑换码集合
        dbCodes.addAll(existingCodes);
        
        return duplicates;
    }
}
